package com.srit.recipes.common.response;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

@Getter
@Setter
@ApiModel
public class JpaPage {
    private Integer pageSize;
    private Integer pageNum;
    @ApiModelProperty(hidden = true)
    private Long totalSize;
    @ApiModelProperty(hidden = true)
    private Object content;

    public static JpaPage build(Page<?> page) {
        JpaPage wxyPage = new JpaPage();
        wxyPage.setContent(page.getContent());
        wxyPage.setPageSize(page.getSize());
        wxyPage.setPageNum(page.getNumber() + 1);
        wxyPage.setTotalSize(page.getTotalElements());
        return wxyPage;
    }

    public static JpaPage build(Page<?> page, Object o) {
        JpaPage wxyPage = new JpaPage();
        wxyPage.setContent(o);
        wxyPage.setPageSize(page.getSize());
        wxyPage.setPageNum(page.getNumber() + 1);
        wxyPage.setTotalSize(page.getTotalElements());
        return wxyPage;
    }

    /**
     * 根据实体类获取分页信息
     */
    public static Pageable getPageable(JpaPage page, Sort sort) {
        sort = sort == null ? Sort.unsorted() : sort;
        if (page == null || page.getPageNum() == null || page.getPageSize() == null) {
            return PageRequest.of(0, 10, sort);
        }
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (pageNum == -1 || pageSize == -1) {
            return PageRequest.of(0, Integer.MAX_VALUE, sort);
        }
        return PageRequest.of(pageNum - 1, pageSize, sort);
    }

    public static Pageable getPageable(JpaPage page) {
        return getPageable(page, null);
    }


}
